<template>
  <div class="app-container">
    <h1>用户信息管理</h1>
    <div id="dialog">
      <div id="editUser">
        <el-dialog
          title="编辑用户信息"
          :visible.sync="editUserVisible"
          center
          width="40%"
        >
          <el-form ref="editUserForm" :model="editUserForm" :rules="editUserRules">
            <el-form-item
              label="工号"
              :label-width="formLabelWidth"
              prop="jobNum"
            >
              <el-input
                v-model="editUserForm.jobNum"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item
              label="用户名"
              :label-width="formLabelWidth"
              prop="userName"
            >
              <el-input
                v-model="editUserForm.userName"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item
              label="邮箱"
              :label-width="formLabelWidth"
              prop="email"
            >
              <el-input
                v-model="editUserForm.email"
                autocomplete="off"
                clearable
              />
            </el-form-item>
            <el-form-item label="部门名称" :label-width="formLabelWidth">
              <el-select
                v-model="editUserForm.companyId"
                filterable
                placeholder="请选择"
              >aaaaa
                <el-option-group
                  v-for="group in departmentOptions"
                  :key="group.label"
                  :label="group.label"
                >
                  <el-option
                    v-for="item in group.options"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId"
                  />
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item
              label="权限身份"
              :label-width="formLabelWidth"
              prop="roles"
            >
              <el-select
                v-model="editUserForm.roles"
                clearable
                multiple
                placeholder="角色"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="入职时间"
              :label-width="formLabelWidth"
              prop="entryTime"
            >
              <el-date-picker
                v-model="editUserForm.entryTime"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item
              label="离职时间"
              :label-width="formLabelWidth"
              prop="departureTime"
            >
              <el-date-picker
                v-model="editUserForm.departureTime"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="editUserVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="updateUserInfo(editUserForm)"
            >确 定
            </el-button>
          </div>
        </el-dialog>
      </div>
      <div id="addUser">
        <el-dialog
          title="新增用户信息"
          :visible.sync="addUserVisable"
          width="40%"
          center
        >
          <el-form
            ref="addUserInfoForm"
            :model="addUserInfoForm"
            :rules="addUserRules"
          >
            <el-form-item
              label="用户名"
              :label-width="formLabelWidth"
              prop="userName"
            >
              <el-input
                v-model="addUserInfoForm.userName"
                autocomplete="off"
                placeholder="请输入用户名"
                clearable
              />
            </el-form-item>
            <el-form-item
              label="工号"
              :label-width="formLabelWidth"
              prop="jobNum"
            >
              <el-input
                v-model="addUserInfoForm.jobNum"
                placeholder="请输入工号"
                clearable
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item
              label="邮箱"
              :label-width="formLabelWidth"
              prop="email"
            >
              <el-input
                v-model="addUserInfoForm.email"
                placeholder="请输入邮箱"
                clearable
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item
              label="部门名称"
              :label-width="formLabelWidth"
              prop="companyId"
            >
              <el-select
                v-model="addUserInfoForm.companyId"
                filterable
                placeholder="请选择部门"
                clearable
              >
                <el-option-group
                  v-for="group in departmentOptions"
                  :key="group.label"
                  :label="group.label"
                >
                  <el-option
                    v-for="item in group.options"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId"
                  />
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item
              label="权限身份"
              :label-width="formLabelWidth"
              prop="roles"
            >
              <el-select
                v-model="addUserInfoForm.roles"
                placeholder="角色"
                filterable
                multiple
                clearable
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-upload
              v-show="readExcelSignal"
              ref="upload"
              v-loading="uploadLoading"
              element-loading-text="拼命解析中..."
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.8)"
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :auto-upload="false"
              :on-change="handleExcelChange"
            >
              <el-button
                slot="trigger"
                size="small"
                type="primary"
              >选取文件
              </el-button>
              <el-button
                style="margin-left: 10px"
                size="small"
                type="success"
                @click="uploadExcel"
              >上传到服务器
              </el-button>
              <div slot="tip" class="el-upload__tip">只能读取excel模板</div>
            </el-upload>
            <el-button @click="addUserVisable = false">取 消</el-button>
            <el-button
              type="primary"
              @click="submitUserInfo('addUserInfoForm')"
            >确 定
            </el-button>
            <el-button @click="openDownLoadDialog">excel导入</el-button>
          </div>
        </el-dialog>
      </div>
      <div id="errorRecord">
        <el-drawer
          title="用户导入记录"
          :visible.sync="RecordDialogVisible"
          direction="rtl"
          :before-close="handleRecordClose"
        >
          <div>
            <span>提示：双击单行，可查看错误记录说明</span>
            <el-table :data="RecordList" @row-dblclick="showErrorRecord">
              <el-table-column label="操作人" prop="userName" labelwidth="180px" align="center" />
              <el-table-column label="导入时间" prop="insertTime" labelwidth="180px" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.insertTime.slice(0,10) }}</span><br>
                  <span>{{ scope.row.insertTime.slice(11,16) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="导入成功" labelwidth="180px" align="center">
                <template slot-scope="scope">
                  {{ scope.row.successNum }}条
                </template>
              </el-table-column>
              <el-table-column label="导入失败" labelwidth="180px" align="center">
                <template slot-scope="scope">
                  {{ scope.row.errorNum }}条
                </template>
              </el-table-column>
            </el-table>
            <div class="f-r">
              <el-pagination
                :current-page.sync="recordListcurrentPage"
                :page-size="RecordListPageData.pageSize"
                layout="total, prev, pager, next"
                :total="RecordListPageData.total"
                @current-change="handleRecordListCurrentChange"
              />
            </div>
            <el-drawer
              title="本次导入的错误记录"
              :append-to-body="true"
              :before-close="handleErrorRecordClose"
              :visible.sync="errorRecordDialogVisible"
            >
              <el-table :data="errorRecordList">
                <el-table-column label="导入时间" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.insertTime.slice(0,10) }}</span><br>
                    <span>{{ scope.row.insertTime.slice(11,16) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="导入用户名" prop="errorUserName" align="center" />
                <el-table-column label="导入失败原因" prop="failReason" align="center" />
                <el-table-column label="错误邮箱" prop="errorUserEmail" align="center" />
                <el-table-column label="错误工号" prop="errorUserJobNum" align="center" />
              </el-table>
              <div class="f-r">
                <el-pagination
                  :current-page.sync="errorRecordListcurrentPage"
                  :page-size="errorRecordListPageData.pageSize"
                  layout="total, prev, pager, next"
                  :total="errorRecordListPageData.total"
                  @current-change="handleErrorRecordListCurrentChange"
                />
              </div>
            </el-drawer>

          </div>
        </el-drawer>
      </div>
    </div>
    <div id="search">
      <!--      :inline="true"-->
      <el-form :model="searchForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.userName" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" />
        </el-form-item>
        <el-form-item label="部门名称">
          <el-select
            v-model="searchForm.companyId"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option-group
              v-for="group in departmentOptions"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.options"
                :key="item.companyId"
                :label="item.companyName"
                :value="item.companyId"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="权限身份">
          <el-select
            v-model="searchForm.roles"
            clearable
            placeholder="角色"
            filterable
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-radio-group v-model="searchForm.userStatus">
            <el-radio-button label="有效" />
            <el-radio-button label="无效" />
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <div class="c-l" />
      </el-form>
    </div>
    <div
      v-loading="tableDataLoading"
      element-loading-text="正在加载用户数据..."
      element-loading-spinner="el-icon-loading"
    >
      <div id="button" class="m-b-10">
        <el-button v-if="roles.includes('企业负责人')" type="primary" @click="goToDM">
          部门管理
        </el-button>
        <el-button type="primary" @click="openRecordDialog">导入记录</el-button>
        <el-button-group class="f-r">
          <el-button
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="openAddUserDiaglog"
          />
          <el-button
            type="warning"
            icon="el-icon-delete"
            @click="updateAllUserStatus(0)"
          />
          <el-button
            type="success"
            icon="el-icon-check"
            @click="updateAllUserStatus(1)"
          />
        </el-button-group>
      </div>
      <div class="m-0">
        <el-table
          :data="tableData"
          tooltip-effect="dark"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
<!--          <el-table-column label="入职时间" align="center" width="120">-->
<!--            <template slot-scope="scope">-->
<!--              <span v-if="scope.row.entryTime!=null&&scope.row.entryTime!='暂无入职时间'">-->
<!--                {{ scope.row.entryTime }}-->
<!--              </span>-->
<!--              <span v-else>-->
<!--                暂无入职时间-->
<!--              </span>-->

<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column prop="departureTime" label="离职时间" align="center" width="120">-->
<!--            <template slot-scope="scope">-->
<!--              <span v-if="scope.row.departureTime!=null&&scope.row.departureTime!='暂无离职时间'">-->
<!--                {{ scope.row.departureTime }}-->
<!--              </span>-->
<!--              <span v-else>-->
<!--                暂无离职时间-->
<!--              </span>-->

<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column prop="jobNum" label="工号" align="center" width="120" />
          <el-table-column prop="gradeId" label="等级" align="center" width="120" />
          <el-table-column prop="grade" label="积分" align="center" width="120" />
          <el-table-column prop="userName" label="用户名" align="center" width="180" />
          <el-table-column prop="email" label="邮箱" align="center " width="180" />
          <el-table-column prop="departmentName" label="部门名称" align="center" width="180" />
          <el-table-column
            label="权限身份"
            align="center"
            width="180"
            :filters="rolelist"
            :filter-method="filterRole"
            filter-placement="bottom-end"
          >
            <template slot-scope="scope">
              <span v-for="role in scope.row.roleNames">
                <el-tag> {{ role }}</el-tag>
              </span>

            </template>
          </el-table-column>
          <el-table-column prop="companyName" label="企业名称" align="center" width="180" />
<!--          <el-table-column-->
<!--            label="标签"-->
<!--            align="center"-->
<!--            width="280"-->
<!--            :filters="taglist"-->
<!--            :filter-method="filterTag"-->
<!--            filter-placement="bottom-end"-->
<!--          >-->
<!--            <template slot-scope="scope">-->
<!--              <span v-for="tag in scope.row.tagNames">-->
<!--                <el-tag type="success">{{ tag }}</el-tag>-->
<!--              </span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column fixed="right" label="操作" align="center" width="240">
            <!--有效员工的操作-->
            <template slot-scope="scope">
              <div v-if="scope.row.status===1">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="editUser(scope.row)"
                />
                <el-button

                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="updateUserStatus(scope.row,0)"
                />
              </div>
              <div v-else>
                <el-button
                  type="success"
                  icon="el-icon-check"
                  circle
                  @click="updateUserStatus(scope.row,1)"
                />
              </div>
            </template>

          </el-table-column>
        </el-table>
      </div>

      <!--用户导入错误弹框-->
      <el-dialog
        title="未成功导入--原因分析"
        :visible.sync="errorInfoDialogVisible"
        width="60%"
        center
      >
        <div style="height: 300px;">
          <el-scrollbar>
            <el-table :data="errorInfo">
              <el-table-column label="邮箱地址" align="center" prop="email" />
              <el-table-column label="用户名" align="center" prop="userName" />
              <el-table-column label="未上传成功原因" align="center">
                <template slot-scope="scope">
                  <span style="color: red;">{{ scope.row.failedReason }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="errorInfoDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="errorInfoDialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div id="page" class="f-r">
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import DropdownMenu from '@/components/Share/DropdownMenu'
import {
  isNull,
  warnInfo,
  successInfo,
  errorInfo,
  getHost,
  getCookie,
  getTokenSign,
  getToken,
  geDownloadUrl,
  getFileType
} from '../../utils/commonUtils.js'
import {
  getUserList,
  getCompanyListWithToken,
  getRoleInfoWithToken,
  updateUserSelective,
  updateUserInfo,
  updateStatusUserByUserIds,
  addUserInfo,
  updateByUserIds,
  getErrorRecordListByPage
} from '../../api/identity.js'
import $ from 'jquery'
import moment from 'moment'
import { mapGetters } from 'vuex'

export default {
  name: 'Documentation',
  components: { DropdownMenu },
  data() {
    return {
      /* 部门管理对话框*/
      departmentDialog: false,
      /* 导入用户，错误信息返回*/
      errorInfoDialogVisible: false,
      errorInfo: [],
      excelFileList: [],
      readExcelSignal: false,
      uploadLoading: false,
      tableDataLoading: false,
      tokenKey: getTokenSign(), // token标识
      token: getToken(), // token
      /** loading */
      lodaingText: undefined,
      loading: false,
      /** edditUser */
      editUserForm: {},
      // jobNum: [{ required: true, message: '请输入工号', trigger: 'blur' }],
      editUserRules: {
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        email: [],
        companyId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        roles: [{ required: true, message: '请选择角色', trigger: 'blur' }],
        entryTime: [],
        departureTime: []
      },
      editUserVisible: false,
      RecordDialogVisible: false,
      errorRecordDialogVisible: false,
      RecordList: [],
      RecordListPageData: {},
      errorRecordList: [],
      errorRecordListPageData: {},
      formLabelWidth: '120px',
      /** table */
      tableData: [],
      multipleSelection: [],
      /** search */
      searchForm: {
        userName: undefined,
        email: undefined,
        jobNum: undefined,
        companyId: undefined,
        roles: undefined,
        userStatus: '有效',
        status: 1,
        page: 1,
        row: 10
      },
      departmentOptions: [],
      otherDempartMentId: '',
      otherDepartMentInfo: {},
      total: 100,
      pageSize: 10,
      currentPage: 1, // 用户信息当前页
      recordListcurrentPage: 1, // 导入记录当前页
      errorRecordListcurrentPage: 1, // 错误导入记录当前页
      switchAdmin: false,
      isAdmin: true,
      /* 这个roleOptions放全部的角色，不绑定表单*/
      roleOptions: [],
      courseMangeRoleId: [],
      /** 新增用户 */
      addUserVisable: false,
      addUserInfoForm: {},
      isCourseManage: false,
      /** 校验 */
      addUserRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        roles: [
          { required: true, message: '请选择用户身份', trigger: 'change' }
        ],
        companyId: [
          { required: true, message: '请选择用户部门', trigger: 'change' }
        ],
        // jobNum: [
        //   { required: true, message: '请输入工号', trigger: 'change' }
        // ],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ]
      },
      otherId: '',
      // /* 标签过滤*/
      // taglist: [
      //   {
      //     text: '注塑',
      //     value: '注塑'
      //   },
      //   {
      //     text: '模具',
      //     value: '模具'
      //   }
      // ],
      /* 角色过滤*/
      rolelist: [
        {
          text: 'admin',
          value: 'admin'
        },
        {
          text: '企业负责人',
          value: '企业负责人'
        },
        {
          text: '部门负责人',
          value: '部门负责人'
        },
        {
          text: '员工',
          value: '员工'
        }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  watch: {
    searchForm: {
      handler: function() {
        /* radio绑定的是label，是字符串，不是数字状态，需要监听修改*/
        const _this = this
        if (_this.searchForm.userStatus == '有效') {
          _this.searchForm.status = 1
        } else if (_this.searchForm.userStatus == '无效') {
          _this.searchForm.status = 0
        }
      },
      deep: true
    },
    errorInfo(val) {
      console.log(val)
      if (val.length != 0) {
        this.errorDialogVisible = true
      }
    },
    addUserInfoForm: {
      // handler:function (){
      //   const _this = this
      //   var roleOptions = this.roleOptions
      //   if(this.addUserInfoForm.companyId==_this.otherId){
      //     this.rolesoptions = roleOptions.filter((data) => {
      //       return (data.companyId == parseInt(_this.otherId))
      //     })
      //   }else{
      //     //如果部门！=其他
      //     this.rolesoptions = roleOptions.filter((data) => {
      //       return (data.companyId != parseInt(_this.otherId))
      //     })
      //   }
      // },
      deep: true
    },
    editUserForm: {
      // handler:function (){
      //   const _this = this;
      //   var roleOptions = this.roleOptions
      //   if(this.editUserForm.companyId==_this.otherId){
      //     this.roleoptions = roleOptions.filter((data) => {
      //       return (data.companyId == _this.otherId)
      //     })
      //   }else{
      //     //如果部门！=其他
      //     this.roleoptions = roleOptions.filter((data) => {
      //       return (data.companyId != _this.otherId)
      //     })
      //   }
      // },
      deep: true
    }

  },
  updated() {
    // if(this.isAdmin==true){
    //   /*如果是超级管理员*/
    // }else{
    //   /*如果不是超级管理员--1.企业负责人权限*/
    //   const _this = this;
    //   this.departmentOptions[0].options.forEach(function(option,index){
    //     if(option.companyName == "其他"){
    //       _this.otherId = option.companyId+"";
    //     }
    //   })
    // }
  },
  created() {
    // 1.获取部门信息
    this.getDepartMentInfos()
    // 2.获取申请列表
    this.getUserList()
    // 3.获取角色列表
    this.getRoleInfoOptions()
  },
  methods: {
    // handleDepartmentChange(val) {
    //   console.log(this.roleOptions)
    //   var roleOptions = this.roleOptions
    //   if (val == 11){
    //     //  如果部门==其他
    //   //  addform过滤掉其他角色，只剩下课程管理员
    //     this.rolesoptions = roleOptions.filter((data) => {
    //       return (data.companyId == 11)
    //     })
    //   }else{
    //     //如果部门！=其他
    //     this.rolesoptions = roleOptions.filter((data) => {
    //       return (data.companyId !=11)
    //     })
    //   }
    // },
    /**
       * handleErrorRecordClose 关闭错误记录抽屉*/
    handleErrorRecordClose() {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.errorRecordDialogVisible = false
          done()
        })
        .catch(_ => {
        })
    },
    /**
       * handleRecordClose 关闭导入记录抽屉*/
    handleRecordClose() {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.RecordDialogVisible = false
          done()
        })
        .catch(_ => {
        })
    },
    /**
       * openRecordDialog 打开导入记录弹窗*/
    openRecordDialog() {
      this.RecordDialogVisible = true
      const recordPagedata = {
        'page': 1,
        'row': 10,
        'pid': 0
      }
      getErrorRecordListByPage(recordPagedata).then((response) => {
        this.RecordList = response.data.list
        this.RecordListPageData = response.data
      })
    },
    /** showErrorRecord 单击导入记录行，出现该行导入的错误记录*/
    showErrorRecord(row) {
      this.errorRecordDialogVisible = true
      const recordPagedata = {
        'page': 1,
        'row': 10,
        'pid': row.importUserRecordId
      }
      getErrorRecordListByPage(recordPagedata).then((response) => {
        this.errorRecordList = response.data.list
        this.errorRecordListPageData = response.data
      })
    },
    /**
       * 打开新增用户对话框
       * */
    openAddUserDiaglog() {
      this.addUserVisable = true
    },
    /* 标签过滤 方法*/
    filterTag(value, row) {
      let findtag = false
      if (row.tagNames.length != 0) {
        row.tagNames.forEach(function(tag, index) {
          if (tag === value) {
            findtag = true
          }
        })
      }
      return findtag
    },
    /* 角色过滤方法*/
    filterRole(value, row) {
      let findrole = false
      if (row.roleNames.length != 0) {
        row.roleNames.forEach(function(role, index) {
          if (value === role) {
            findrole = true
          }
        })
      }
      return findrole
    },
    /* 跳转到部门管理*/
    goToDM() {
      this.$router.push({
        name: 'departmentManagement'
      })
    },
    uploadExcel() {
      const _this = this
      if (this.excelFileList.length >= 1) {
        _this.uploadLoading = true
        const formData = new FormData()
        formData.append('multipartFile', this.excelFileList[0].raw)
        $.ajax({
          url: getHost() + '/indentity/user/addUserInfoByExcel',
          data: formData,
          dataType: 'json',
          type: 'post',
          processData: false, // 告诉jQuery不要去处理发送的数据
          contentType: false, // 告诉jQuery不要去设置Content-Type请求头
          // 加上这句话,允许浏览器向服务器跨域请求时携带cookie
          xhrFields: {
            withCredentials: true
          },
          crossDomain: true,
          beforeSend: function(request) {
            request.setRequestHeader(_this.tokenKey, _this.token)
          },
          success: function(response) {
            _this.readExcelSignal = false
            _this.uploadLoading = false
            _this.addUserVisable = false
            // 重新拉取数据
            // 2.获取申请列表
            _this.getUserList()
            // if (response.data.insertNum != 0) {
            //   successInfo(_this, "成功上传" + response.data.insertNum + "道题目");
            // } else if (response.data.errorNum != 0) {
            //   _this.errorInfo = response.data.errorInfo;
            // }
            _this.$refs['upload'].clearFiles()
            // _this.uplaodSignal = false;
            // _this.uploadLoading = false;

            // _this.excelFileList = [];
            // _this.$refs["upload"].clearFiles();
            // successInfo(_this, "成功上传" + data.data + "道题目");
          },
          error: function(data) {
          }
        })
      } else {
        warnInfo(_this, '您未选择任何文件')
        return false
      }
    },
    handleRemove(file, fileList) {
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleExcelChange(file, fileList) {
      const _this = this
      if (getFileType(file.name) == 'xlsx' || getFileType(file.name) == 'xls') {
        if (fileList.length == 1) {
          this.excelFileList = fileList
        } else if (fileList.length > 1) {
          fileList.pop(file)
          warnInfo(_this, '一次只能上传一个文件')
        }
      } else {
        warnInfo(_this, '文件格式错误')
        fileList.pop(file)
      }
    },
    openDownLoadDialog() {
      const _this = this
      this.$confirm('只能导入指定excel模板，是否下载?', '提示', {
        confirmButtonText: '下载模板',
        cancelButtonText: '继续导入',
        type: 'warning'
      })
        .then(() => {
          _this.readExcelSignal = true
          // window.open(geDownloadUrl().userExcelDemo);
          window.open(geDownloadUrl().userExcelDemo)
        })
        .catch(() => {
          _this.readExcelSignal = true
        })
    },
    /** 处理部门列表信息 */
    dealDempartmentOptions() {
      const _this = this
      if (
        _this.departmentOptions[0].options.includes(_this.otherDepartMentInfo)
      ) {
        _this.departmentOptions[0].options.pop(_this.otherDepartMentInfo)
      }
    },
    /**
       * 当选中角色为课程管理员时
       */
    dealCourseMange(roleId) {
      const _this = this
      // if (this.courseMangeRoleId.includes(roleId)) {
      //   _this.isCourseManage = true;
      //   _this.departmentOptions[0].options.push(_this.otherDepartMentInfo);
      // } else {
      //   _this.isCourseManage = false;
      //   this.dealDempartmentOptions();
      // }
    },
    /** 工具方法 */
    // 处理多选将其变为一个仅含userId的列表
    dealMultipleSelection(status) {
      const _this = this

      var userData = []
      $(_this.multipleSelection).each(function(index, value) {
        userData.push({
          userId: value.userId,
          status: status
        })
      })
      return userData
    },
    /** 更新所有选中的用户信息：0-无效，1-有效 */
    updateAllUserStatus(status) {
      const _this = this
      if (status == 0) {
        if (this.multipleSelection.length <= 0) {
          warnInfo(_this, '您未选择任何用户数据')
        } else {
          this.$confirm(
            '确认注销所有选中用户?',
            '提示',
            {
              confirmButtonText: '注销',
              cancelButtonText: '再想想',
              type: 'warning'
            }
          )
            .then(() => {
              _this.lodaingText = '正在注销中...'
              _this.loading = true
              const query = _this.dealMultipleSelection(status)
              updateStatusUserByUserIds(query).then((response) => {
                // 重新拉取数据
                _this.getUserList()
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消注销'
              })
            })
        }
      } else if (status === 1) {
        if (this.multipleSelection.length <= 0) {
          warnInfo(_this, '您未选择任何用户数据')
        } else {
          this.$confirm(
            '确认恢复所有选中用户?',
            '提示',
            {
              confirmButtonText: '恢复',
              cancelButtonText: '再想想',
              type: 'warning'
            }
          )
            .then(() => {
              _this.lodaingText = '正在恢复中...'
              _this.loading = true
              const query = _this.dealMultipleSelection(status)
              updateStatusUserByUserIds(query).then((response) => {
                // 重新拉取数据
                _this.getUserList()
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消恢复'
              })
            })
        }
      }
    },
    /** 新增用户 */
    submitUserInfo(form) {
      const _this = this
      const rolesArray = _this.addUserInfoForm.roles.join(',')
      this.$refs[form].validate((valid) => {
        if (valid) {
          // 新增用户信息
          _this.addUserInfoForm.status = 1// 新增用户默认为有效用户
          _this.addUserInfoForm.roles = rolesArray
          addUserInfo(_this.addUserInfoForm).then((response) => {
            // 清除信息
            _this.addUserVisable = false
            _this.$message({
              message: '用户' + _this.addUserInfoForm.userName + '添加成功',
              type: 'success'
            })
            _this.addUserInfoForm = {}
            // 重新拉取数据
            // 2.获取申请列表
            _this.getUserList()
          })
        }
      })
    },
    /** 一键通过 */
    adoptAll() {
      const _this = this
      if (this.multipleSelection.length <= 0) {
        warnInfo(_this, '您未选择任何用户数据')
      } else {
        const query = {
          status: 1,
          userIds: _this.dealMultipleSelection(status)
        }
        updateByUserIds(query).then((response) => {
          // 1.获取申请列表
          this.getUserList()
        })
      }
    },
    /** 监听表格的选中状态 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /**
       * 更新用户状态：0-无效；1-有效
       */
    updateUserStatus(row, status) {
      if (status === 0 && row.status === 1) {
        this.$confirm('确认注销该用户?', '提示', {
          confirmButtonText: '注销',
          cancelButtonText: '再想想',
          type: 'warning'
        })
          .then(() => {
            this.lodaingText = '正在注销中...'
            this.loading = true
            const userStatusData = {
              'status': status,
              'userId': row.userId
            }
            updateUserInfo(userStatusData).then((response) => {
              // 2.获取申请列表
              this.getUserList()
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消注销'
            })
          })
      } else if (status === 1 && row.status === 0) {
        this.$confirm('确认恢复该用户?', '提示', {
          confirmButtonText: '恢复',
          cancelButtonText: '再想想',
          type: 'warning'
        })
          .then(() => {
            this.lodaingText = '正在恢复中...'
            this.loading = true
            const userStatusData = {
              'status': status,
              'userId': row.userId
            }
            updateUserInfo(userStatusData).then((response) => {
              // 2.获取申请列表
              this.getUserList()
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消恢复'
            })
          })
      }
    },
    /**
       * 编辑用户信息
       */
    editUser(row) {
      const _this = this
      this.editUserForm = JSON.parse(JSON.stringify(row))// 深拷贝，防止引用到同一个对象
      // 处理注册身份，部门名称
      const roles = row.roles.split(',')
      this.editUserForm.roles = []
      const newRoles = new Array()
      if (row.roles != null || row.roles != '') {
        roles.forEach(function(role, index) {
          _this.editUserForm.roles.push(parseInt(role))
        })
      }
      this.editUserForm.companyId = parseInt(this.editUserForm.companyId)
      // this.editUserForm.entryTime = null;
      // this.editUserForm.departureTime = null;
      this.editUserVisible = true
    },
    updateUserInfo(editUserForm) {
      /* 处理角色为string，以“，”分割*/
      editUserForm.roles = editUserForm.roles.toString()
      /* 若离职入职时间为null，修改为空字符串*/
      if (editUserForm.entryTime == null) {
        editUserForm.entryTime = ''
      }
      if (editUserForm.departureTime == null) {
        editUserForm.departureTime = ''
      }
      this.$refs['editUserForm'].validate((valid) => {
        if (valid) {
          // 更新用户信息
          updateUserSelective(this.editUserForm).then((response) => {
            // 2.获取申请列表
            this.getUserList()
            this.editUserVisible = false
          })
        }
      })
    },
    /**
       * 获取角色列表
       */
    getRoleInfoOptions() {
      const _this = this
      getRoleInfoWithToken().then((response) => {
        console.log(response)
        _this.roleOptions = response.data
      })
    },
    /**
       * 获取部门信息
       * **/
    getDepartMentInfos() {
      const _this = this
      getCompanyListWithToken().then((response) => {
        _this.departmentOptions = response.data
      })
    },
    /**
       * 处理页面的变化
       * **/
    handleCurrentChange(val) {
      this.currentPage = val
      // 拉取数据
      this.getUserList()
    },
    handleRecordListCurrentChange(val) {
      this.RecordListcurrentPage = val
      // 拉取数据
    },
    handleErrorRecordListCurrentChange(val) {
      this.errorRecordListcurrentPage = val
      // 拉取数据
    },
    /**
       * 提交查询
       * **/
    onSubmit() {
      const _this = this
      if (!isNull(this.searchForm.applyTimeStr)) {
        _this.searchForm.startTime = moment(
          this.searchForm.applyTimeStr[0]
        ).format('YYYY-MM-DD')
        _this.searchForm.endTime = moment(
          this.searchForm.applyTimeStr[1]
        ).format('YYYY-MM-DD')
      } else {
        _this.searchForm.startTime = undefined
        _this.searchForm.endTime = undefined
      }
      this.getUserList()
    },
    /**
       * 获取用户列表
       * **/
    getUserList() {
      const _this = this
      this.searchForm.page = this.currentPage
      this.searchForm.row = this.pageSize
      _this.tableDataLoading = true
      getUserList(_this.searchForm).then((response) => {
        _this.loading = false
        _this.total = response.data.total
        _this.tableData = response.data.list
        $(_this.tableData).each(function(index, value) {
          /* 入职时间处理*/
          if (value.entryTime != null) {
            _this.tableData[index].entryTime = moment(value.entryTime).format(
              'YYYY-MM-DD'
            )
          }
          /* 离职时间处理*/
          if (value.departureTime != null) {
            _this.tableData[index].departureTime = moment(value.departureTime).format(
              'YYYY-MM-DD'
            )
          }
        })
        _this.tableDataLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "../../styles/common.css";

  #search .el-form-item {
    float: left;
    width: auto;
  }

  .el-tag {
    margin: 5px;
  }

  #editUser .el-form, #addUser .el-form {
    width: 80%;
    margin: 0 auto;
  }
</style>
